#include <iostream>
#include <sys/shm.h>
#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
 
#define image_size_max 576*768*3
struct shareMemory {
    int pixel_rows;
    int pixel_cols;
    int pixel_channels;
    char pixel[image_size_max];
};
 
using namespace cv;
using namespace std;
 
struct shareMemory *get_shared_memory() {
    int shmid = shmget((key_t) 2232, sizeof(struct shareMemory), 0666 | IPC_CREAT);
    if (shmid == -1) {
        fprintf(stderr, "shmget failed\n");
        exit(EXIT_FAILURE);
    }
    //将共享内存连接到当前进程的地址空间
    void *shm = shmat(shmid, NULL, 0);
    if (shm == (void *) -1) {
        fprintf(stderr, "shmat failed\n");
        exit(EXIT_FAILURE);
    }
 
    struct shareMemory *shared = (struct shareMemory *) shm;
    return shared;
 
}
 
char *Mat_to_array(Mat Image) {
    char *pBuffet = new char[Image.cols * Image.rows * 3];
    if (Image.isContinuous()) {
        memcpy(pBuffet, Image.data, Image.cols * Image.rows * 3);
    } else {
        for (int i = 0; i < Image.rows; ++i) {
            memcpy(pBuffet, Image.ptr<uchar>(i), Image.cols * 3);
        }
    }
    return pBuffet;
}
 
int main() {
 
    Mat Image = imread("/home/ubuntu/Downloads/dog.jpg");
    struct shareMemory *shareMemory = get_shared_memory();
    char *image=(char*)Image.data;
    shareMemory->pixel_rows = Image.rows;
    shareMemory->pixel_cols = Image.cols;
    shareMemory->pixel_channels = Image.channels();
    memcpy(shareMemory->pixel,image,Image.rows*Image.cols*3);
    std::cout << "width=" << Image.rows << endl
              << "height=" << Image.cols << endl
              << "channel=" << Image.channels() << endl;
    return 0;
}
